// pages/student/qingjiajilu/qingjiajilu.js
Page({
  data: {
    leaveRecords: [],
    isLoading: false,
    isEmpty: false
  },

  onLoad: function() {
    this.fetchLeaveRecords();
  },

  onShow: function() {
    // 页面显示时刷新数据
    this.fetchLeaveRecords();
  },

  // 获取请假记录
  fetchLeaveRecords: function() {
    this.setData({
      isLoading: true
    });

    wx.showLoading({
      title: '加载中...',
    });

    // 获取用户信息和token
    const userInfo = wx.getStorageSync('userInfo') || {};
    const token = wx.getStorageSync('token');

    // 调用后端API获取请假记录
    wx.request({
      url: 'http://localhost:3000/api/leaves/student',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + token
      },
      success: (res) => {
        wx.hideLoading();
        this.setData({
          isLoading: false
        });

        if (res.statusCode === 200 && res.data.success) {
          // 处理返回的数据
          const records = res.data.leaves || [];
          
          // 格式化数据
          const formattedRecords = records.map(item => {
            return {
              id: item.id,
              type: item.type,
              status: this.formatStatus(item.status),
              startDate: item.startDate,
              endDate: item.endDate,
              duration: item.days + '天',
              reason: item.reason,
              approver: item.approverId ? item.approverName : '待审批'
            };
          });

          this.setData({
            leaveRecords: formattedRecords,
            isEmpty: formattedRecords.length === 0
          });
        } else {
          this.setData({
            leaveRecords: [],
            isEmpty: true
          });
          
          wx.showToast({
            title: res.data.message || '获取请假记录失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.hideLoading();
        this.setData({
          isLoading: false,
          isEmpty: true
        });
        
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 格式化请假状态
  formatStatus: function(status) {
    switch(status) {
      case 'pending': return '待审批';
      case 'approved': return '已批准';
      case 'rejected': return '已拒绝';
      default: return status;
    }
  },

  // 查看请假详情
  viewDetail: function(e) {
    const id = e.currentTarget.dataset.id;
    console.log('跳转到请假详情，ID:', id);
    
    // 跳转到请假详情页面
    wx.navigateTo({
      url: '/pages/student/qingjiaxiangqing/qingjiaxiangqing?id=' + id,
      fail: function(res) {
        console.error('跳转失败:', res);
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  }
});